<template>
	<view class="addTeam">
		<uni-forms ref="form" :modelValue="formData">
			<uni-forms-item label="队伍名字" required>
				<uni-easyinput v-model="formData.teamName" placeholder="请输入队伍名字" maxlength="15" />
			</uni-forms-item>
			<uni-forms-item label="联系方式" required>
				<uni-easyinput v-model="formData.connect" placeholder="请输入手机联系方式" maxlength="11" />
			</uni-forms-item>
			<uni-forms-item label="队伍人数" required>
				<uni-easyinput v-model="formData.teamNum" type="number" placeholder="请输入队伍总人数" maxlength="3" />
			</uni-forms-item>
			<uni-forms-item label="队伍情况" required>
				<uni-easyinput type="textarea" v-model="formData.situation" placeholder="请输入队伍情况(150字内)"
					maxlength="150" />
			</uni-forms-item>
			<uni-forms-item label="队伍目标" required>
				<uni-easyinput type="textarea" v-model="formData.goal" placeholder="请输入队伍目标(150字内)" maxlength="150" />
			</uni-forms-item>
			<uni-forms-item label="招收对象" required>
				<uni-easyinput type="textarea" v-model="formData.recruit" placeholder="请输入招收对象(150字内)"
					maxlength="150" />
			</uni-forms-item>
			<uni-forms-item label="对投稿者的要求" required>
				<uni-easyinput type="textarea" v-model="formData.recruitNeed" placeholder="请输入对投稿者的要求(150字内)"
					maxlength="150" />
			</uni-forms-item>
			<uni-forms-item label="请选择类型" required>
				<uni-data-checkbox v-model="formData.type" :localdata="type" />
			</uni-forms-item>
			<uni-forms-item label="贴标签" required>
				<view class="tagsList">
					<template v-for="(item,index) in formData.tags">
						<tag :name='item' :data-index="index" @click.native="delt(index)"></tag>
					</template>
				</view>
				<view class="jiahao" @click="tianjia">
					<image src="/static/jiahao.png" mode=""></image>
				</view>
			</uni-forms-item>
			<uni-forms-item label="请选择队伍类型" required>
				<uni-data-checkbox v-model="formData.teamType" :localdata="itemType" @change="handleteamType" />
			</uni-forms-item>
			<uni-forms-item label="项目名字" required v-if="!isPingTai">
				<uni-easyinput v-model="formData.teamProjectName" placeholder="请输入自定义的项目或比赛或其他的名字" maxlength="20" />
			</uni-forms-item>
			<uni-forms-item :label="formData.teamType == 1 ? '选择比赛' : '选择项目'" required v-if="isPingTai">

				<picker v-if="formData.teamType == 1" mode="multiSelector" @columnchange="handleColumnChange"
					@change="pickerChange" :value="multiIndex" @cancel="pickerChangecancel" :range="competionTree"
					:range-key="rangekey">
					<view class="uni-input space-between" hover-class="hover-color">
						{{ competionTree[0][Index1] }} ---
						{{ competionTree[1][Index2]  }}
					</view>
				</picker>
				<picker v-else @change="handleItmeColumnChange" :value="ItemIndex" :range="projectTree">
					<view class="uni-input">{{projectTree[ItemIndex]}}</view>
				</picker>


			</uni-forms-item>
			<uni-forms-item>
				<button type="primary" :disabled="isLoading" @click="submit" class="w100"
					:loading="isLoading">提交</button>
			</uni-forms-item>
		</uni-forms>

		<modal v-if="areaShow" @cancel="cancelAdd" @confirm="confirmAdd" title="新增标签" confirm-text="保存"
			cancel-text="取消">
			<input type="text" v-model="areaTxt" placeholder="填写你想加的标签" class="intxt" maxlength="10" />
		</modal>
		<modal v-if="del" @cancel="canceldel" @confirm="confirmdel" title="是否删除此标签？" confirm-text="删除" cancel-text="取消">
		</modal>
	</view>
</template>

<script>
	import tag from "@/components/tag/index.vue";
	export default {
		components: {
			tag
		},
		data() {
			return {
				savedIndex1: 0,
				Index1: 0,
				Index2: 0,
				ItemIndex: 0,
				multiIndex: [0, 0, 0],
				value: [],
				isPingTai: true,
				areaTxt: '', //收集标签
				isLoading: false,
				areaShow: false, //提示添加的标签框
				index: '', //标签序号
				del: false, //提示删除的标签框
				projectId: 0,
				formData: {

					situation: '', //队伍情况
					goal: '', //队伍目标
					recruit: '', //招收对象
					recruitNeed: '', //对投稿者的要求
					connect: '', //联系方式
					type: 0, //类型
					teamProjectName: '', //项目名字
					teamType: 1, //组队类型
					tags: [], //标签
					teamNum: '', //队伍人数
					teamName: '' //队伍名字
				},
				//类型
				type: [{
						"value": 0,
						"text": "个人"
					},
					{
						"value": 1,
						"text": "组织"
					}
				],
				competionTree: [
					[],
					[]
				],
				projectTree: ['选择项目'],
				dataTree: [],
				dataTreeSecond: [],
				newItmeList: [],
				// 组队类型
				itemType: [{
						value: 1,
						text: '平台比赛'
					},
					{
						value: 2,
						text: '平台项目'
					},
					{
						value: 3,
						text: '自定义比赛'
					}, {
						value: 4,
						text: '自定义项目'
					}, {
						value: 5,
						text: '其他'
					},
				]
			};
		},
		methods: {
			pickerChangecancel(e) {
				this.Index1 = this.savedIndex1

			},
			handleItmeColumnChange(e) {
				const value = e.detail.value
				this.ItemIndex = value
			},
			async bingds(data) {

				try {
					uni.showLoading({
						title: '加载中...'
					})
					const result = await this.$mjcrequest.request({
						url: this.$api.bindProJ,
						data: JSON.stringify(data),
						header: this.$aplsjsonheader,
						isToast: true
					})
					this.$setTimeoutback()
				} catch (e) {
					uni.hideLoading();
					this.$errMessageToast(e)
					//TODO handle the exception
				}
			},
			handleColumnChange(e) {
				console.log(e, 147);
				const column = e.detail.column //列
				const value = e.detail.value //选中列的索引
				if (column == 0 && value == 0) {
					this.nodataColumn2()
					return
				}

				switch (column) {
					case 0:
						//第一列，请求当前比赛的数据
						const name = this.dataTree[value - 1].text
						this.savedIndex1 = value
						this.initalNodataColumn2()
						this.$nextTick(() => {
							this.getDataCompetion(name)
						})


						break;

					case 1:

						break;

				}
			},
			pickerChange(e) {
				console.log(e, 173);
				this.Index1 = e.detail.value[0]
				this.Index2 = e.detail.value[1]
			},
			bingdProject(teamId) {
				let data = null;
				if (this.formData.teamType == 1) {
					const projectItem = this.dataTreeSecond.filter(item => {
						return item.projectName == this.competionTree[1][this.Index2]
					})
					if (projectItem.length == 0) {
						this.$errMessageToast('获取比赛信息错误，请重试。')
						return
					}
					if (projectItem.length > 1) {
						this.$errMessageToast('所选择的比赛有重名情况，请重试。')
						return
					}
					data = {
						teamId: String(teamId),
						projectId: String(projectItem[0].projectId)
					}
				} else {
					const projectItem = this.newItmeList.filter(item => {

						console.log(item, 182);
						return item.projectName == this.projectTree[this.ItemIndex]
					})
					if (projectItem.length == 0) {
						this.$errMessageToast('获取项目信息错误，请重试。')
						return
					}
					if (projectItem.length > 1) {
						this.$errMessageToast('所选择的项目有重名情况，请重试。')
						return
					}
					data = {
						teamId: String(teamId),
						projectId: String(projectItem[0].projectId)
					}
				}
				this.bingds(data)
			},
			async getDataCompetion(name) {

				try {
					let data = {
						createDepartment: name,
						endDate: null,
						instituteType: null,
						pageNum: 1,
						pageSize: 999
					}
					const result = await this.$mjcrequest.request({
						url: this.$api.getMygetGame,
						data: JSON.stringify(data),
						header: this.$aplsjsonheader,
					})
					if (result.total == 0) {
						//无数据
						this.nodataColumn2()
						return
					}
					const newresult = this.filterList(result)
					console.log(newresult, 200);
					this.$set(this.competionTree, 1, newresult)

				} catch (e) {
					//TODO handle the exception
					this.$errMessageToast(e)
				}
			},
			nodataColumn2() {
				this.$set(this.competionTree, 1, ['暂无比赛'])

			},
			initalNodataColumn2() {
				this.$set(this.competionTree, 1, [])
				this.Index1 = 0

			},
			filterList(list) {
				//处理列表数据
				let newList = []
				let dataTreeSecond = []
				newList = list.pageDate.map(item => {
					return item.project.projectName
				})
				dataTreeSecond = list.pageDate.map(item => {
					return {
						projectName: item.project.projectName,
						projectId: item.project.projectId
					}
				})
				this.dataTreeSecond = dataTreeSecond
				return newList
			},
			filterItemList(list) {
				//处理列表数据
				let newList = []
				let newItmeList = []
				newList = list.pageDate.map(item => {
					return item.project.place
				});
				newItmeList = list.pageDate.map(item => {
					return {
						projectName: item.project.projectName,
						projectId: item.project.projectId
					}
				})
				this.newItmeList = newItmeList
				return ['选择项目', ...newList]
			},
			// 提交
			async submit() {
				try {
					if (this.vaildType()) {
						let data = {
							...this.formData
						}
						this.isLoading = true
						const result = await this.$mjcrequest.request({
							url: this.$api.addTeam,
							data: JSON.stringify(data),
							header: this.$aplsjsonheader,
							isToast: true
						})
						if (!this.isPingTai) {
							this.$setTimeoutback()
							return
						}
						const teamId = result.teamId
						this.bingdProject(teamId)
					}

				} catch (errMessage) {
					this.isLoading = false
					//TODO handle the exception
					this.$errMessageToast(errMessage.message || errMessage)
				}
			},
			// 标签添加
			tianjia() {
				this.areaShow = true
			},
			// 标签删除
			delt(index) {
				this.del = true
				this.index = index
			},
			// 确认删除标签
			confirmdel() {
				this.formData.tags.splice(this.index, 1)
				this.del = false
			},
			// 确认添加标签
			confirmAdd(e) {

				if (this.areaTxt.length == 0 || this.areaTxt.trim() == '') {

					this.$errMessageToast('不能为空')
					return
				}
				if (this.formData.tags != null) {

					if (this.formData.tags.indexOf(this.areaTxt) != -1) {
						this.$errMessageToast('有重复的标签')
						return
					}

					if (this.formData.tags.length == 6) {
						this.$errMessageToast('标签最多6个')
						return
					}

				}
				this.formData.tags.push(this.areaTxt.trim())
				this.areaTxt = ''
				this.areaShow = false
			},
			//取消添加标签
			cancelAdd() {
				this.areaShow = false
				this.areaTxt = ''
			},
			// 取消删除标签
			canceldel() {
				this.del = false
			},
			async handleteamType(e) {
				const value = e.detail.value
				this.formData.teamType = value
				if (value == 1 || value == 2) {
					this.isPingTai = true
					this.formData.teamProjectName = ''
				} else {
					this.isPingTai = false
					this.formData.teamProjectName = ''
				}
				if (value == 2 && this.projectTree.length == 1) {
					const data = {
						content: null,
						tags: null,
						projectStartTime: null,
						instituteType: 2,
						pageNum: 1,
						pageSize: 999
					}
					const result = await this.$mjcrequest.request({
						url: this.$api.getProject,
						data: JSON.stringify(data)
					})
					if (result.total == 0) return
					this.projectTree = this.filterItemList(result)
					console.log(this.projectTree, 380);
				}
			},
			// 表单验证
			vaildType() {
				if (this.formData.teamName == '' || this.formData.teamName == undefined) {
					throw new Error('请输入队伍名字')
				}
				if (this.formData.connect == '' || this.formData.connect == undefined) {
					throw new Error('请填写联系方式')
				}
				if (!(/^1[3456789]\d{9}$/.test(this.formData.connect))) {

					throw new Error('发布人联系方式有误，请重填')
				}
				if (this.formData.teamNum == '' || this.formData.teamNum == undefined) {

					throw new Error('请填写队伍人数')
				}
				if (this.formData.situation == '' || this.formData.situation == undefined) {

					throw new Error('请填写队伍情况')
				}
				if (this.formData.goal == '' || this.formData.goal == undefined) {

					throw new Error('请填写队伍目标')
				}


				if (this.formData.recruit == '' || this.formData.recruit == undefined) {
					throw new Error('请输入招收对象')
				}
				if (this.formData.recruitNeed == '' || this.formData.recruitNeed == undefined) {
					throw new Error('请输入对投稿者的要求')
				}
				if (this.formData.tags.length == 0) {
					throw new Error('请添加至少一个标签')
				}

				if (this.formData.teamProjectName == '' || this.formData.teamProjectName == undefined) {
					if (!this.isPingTai) {
						throw new Error('请填写项目名字')
					}
				}
				if (this.isPingTai) {
					//平台类的
					//比赛
					if (this.formData.teamType == 1) {
						if (this.Index1 == 0 & this.Index2 == 0) {
							throw new Error('请选择平台比赛绑定')
						}
						if (this.competionTree[1][this.Index2] == '暂无比赛') {
							throw new Error('请选择平台具体比赛绑定')
						}
					}
					if (this.formData.teamType == 2) {
						//项目
						if (this.ItemIndex == 0 && this.projectTree.length != 0) {
							throw new Error('请选择平台具体项目绑定')
						}
						if (this.ItemIndex == 0 && this.projectTree.length == 0) {
							throw new Error('平台暂无项目，请选择自定义或者发布项目通过后再绑定')
						}

					}
				}
				return true
			},
		},
		async created() {
			const nel = uni.getStorageSync("newList");
			if (!nel) {
				const result = await this.$mjcrequest.request({
					url: this.$api.getInstituteDic,
					data: JSON.stringify(data),
					header: this.$aplsjsonheader,
				});
				console.log(result);
				const newList = result.pageDate.map((item) => {
					return {
						text: item.instituteName,
						value: item.instituteName,
						instituteId: item.instituteId,
					};
				});
				uni.setStorageSync("newList", newList);
				this.dataTree = newList.filter(item => {
					if (item.text != '不限') {
						return true
					} else {
						return false
					}
				});
			} else {
				this.dataTree = nel.filter(item => {
					if (item.text != '不限') {
						return true
					} else {
						return false
					}
				});
			}
			this.$nextTick(() => {
				const list = this.dataTree.map(item => {
					return item.text
				})
				const newArray = ['选择学院', ...list]
				const newArray2 = ['选择比赛'];
				console.log(newArray, 310);
				this.$set(this.competionTree,
					0, newArray);
				this.$set(this
					.competionTree, 1, newArray2)
			})

		}
	}
</script>

<style lang="scss">
	.addTeam {
		height: auto;
		padding: 10rpx 20rpx 15rpx 20rpx;
		background-color: #fff;

		.tagsList {
			max-width: calc(100% - 25rpx) !important;
			width: auto;
		}

		.fileUpload {
			display: flex;
			flex-direction: column;
			flex-wrap: wrap;

			& .fileUploadList {
				display: flex;
				flex-wrap: wrap;
			}
		}

		.jiahao {
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			overflow: hidden;

			& image {
				width: 100%;
				height: 100%;
			}
		}

		.uni-forms-item__content {
			display: flex;
			align-items: center;
		}

		.w100 {
			width: 100%;
		}
	}
</style>
